package ru.kruzhki.client.ui.searchresults;

import java.util.List;

import ru.kruzhki.client.gwt.MaskableView;
import ru.kruzhki.client.gwtp.GwtpUtil;
import ru.kruzhki.client.place.NameTokens;
import ru.kruzhki.client.rpc.MaskCallback;
import ru.kruzhki.client.ui.main.MainPagePresenter;
import ru.kruzhki.shared.command.SearchCompanyRequest;
import ru.kruzhki.shared.command.SearchCompanyResponse;
import ru.kruzhki.shared.model.Company;

import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.dispatch.shared.DispatchAsync;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;

public class SearchResultsPresenter extends
Presenter<SearchResultsPresenter.MyView, SearchResultsPresenter.MyProxy> {

	public enum MyParam{
		SEARCH_TEXT;
	}
	public interface MyView extends MaskableView {
		void setSearchResults(List<Company> companies);
	}

	@ProxyCodeSplit
	@NameToken(NameTokens.response)
	public interface MyProxy extends ProxyPlace<SearchResultsPresenter> {
		//
	}


	private final DispatchAsync dispatcher;



	@Inject
	public SearchResultsPresenter(final EventBus eventBus, final MyView view,
			final MyProxy proxy, final DispatchAsync dispatcher) {
		super(eventBus, view, proxy);

		this.dispatcher = dispatcher;
	}

	@Override
	protected void revealInParent() {
		RevealContentEvent.fire(this, MainPagePresenter.TYPE_content, this);
	}


	@Override
	protected void onBind() {
		super.onBind();
	}

	@Override
	protected void onReset() {
		super.onReset();

		String searchText = GwtpUtil.getParam(MyParam.SEARCH_TEXT);
		dispatcher.execute(new SearchCompanyRequest(), new MaskCallback<SearchCompanyResponse>(getView()) {

			@Override
			protected void onSuccessInternal(SearchCompanyResponse result) {
				getView().setSearchResults(result.getItems());
			}
		});
	}
}
